<template>
    <div>
        <el-dialog :title="props.isAdd ? '添加管理员' : '编辑管理员'" center v-model="props.isShow" :before-close="beforeClose">
            <el-form :model="userForm" :rules="rules" ref="userRef">
                <el-form-item label="所属角色" :label-width="formLabelWidth" prop="roleid">
                    <el-select v-model="userForm.roleid" placeholder="请选择">
                        <el-option v-for="item in store.getters['role/getRole']" :key="item.id" :label="item.rolename"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名称" :label-width="formLabelWidth" prop="username">
                    <el-input v-model="userForm.username" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="userForm.password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="userForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(userRef)">取消</el-button>
                    <el-button type="primary" @click="sure(userRef)">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, defineExpose, defineEmits, ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { userAdd, userEdit, userInfo } from '../../request/api'
// import store from '@/store'
import {useStore} from 'vuex'
let store = useStore()

let newId = 0

//父传子 接收数据
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

//子传父
let emit = defineEmits(['cancel'])

let userForm = ref({
    roleid: '',//角色编号number
    username: '',//管理员名称string
    password: '',//密码string
    status: 1,//状态  1正常2禁用number
})

//取消x事件
const beforeClose = (done: any) => {
    done()
    cancel(userRef.value)
}

//封装一个取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    userForm.value = {
        roleid: '',//角色编号number
        username: '',//管理员名称string
        password: '',//密码string
        status: 1,//状态  1正常2禁用number
    }
    //清除表单验证
    formEl.resetFields()
}

const userRef = ref<FormInstance>()
//添加事件
const sure = async (formEl?: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(val => {
        if (val) {
            console.log(userForm.value, '管理员表单');
            if (props.isAdd) {
                userAdd(userForm.value).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('user/getUserListActions')
                        roleList()
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                userEdit({...userForm.value,id:newId}).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('user/getUserListActions')
                        roleList()
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

const formLabelWidth = '140px'

const rules = reactive<FormRules>({
    roleid: [
        {
            required: true,
            message: '请选择角色',
            trigger: 'change',
        }
    ],
    username: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' },
    ]
})


//数据回显
const lookup = (uid: number) => {
    userInfo({ uid }).then((res: any) => {
        // console.log(id);    
        userForm.value = res.list
        // console.log(res);
        newId = uid
        //注意：如果 密码为空则不做修改
        userForm.value.password = ''
    })
}

defineExpose({
    lookup
})

//判断角色管理的长度等于0就调用列表行动，减少调用浪费
const roleList = () => {
    if (store.getters['role/getRole'].length == 0) {
        store.dispatch('role/getRoleListActions')
    }
}
roleList()
</script>
<style lang='less' scoped></style>